const express = require('express');
const router = express.Router();
const { User } = require('../../models');
const { success, error } = require('../../utils/response');
const { Op, fn, col, literal } = require('sequelize');

// 获取每月用户注册数量
router.get('/monthly-registrations', async (req, res) => {
    try {
        const year = req.query.year || new Date().getFullYear();
        
        const statistics = await User.findAll({
            attributes: [
                [fn('DATE_FORMAT', col('createdAt'), '%Y-%m'), 'month'],
                [fn('COUNT', '*'), 'count']
            ],
            where: {
                createdAt: {
                    [Op.between]: [
                        `${year}-01-01`,
                        `${year}-12-31`
                    ]
                }
            },
            group: [fn('DATE_FORMAT', col('createdAt'), '%Y-%m')],
            order: [[col('month'), 'ASC']],
            raw: true
        });

        // 填充没有数据的月份
        const fullYearData = Array.from({ length: 12 }, (_, index) => {
            const month = String(index + 1).padStart(2, '0');
            const existingData = statistics.find(item => item.month === `${year}-${month}`);
            return {
                month: `${year}-${month}`,
                count: existingData ? existingData.count : 0
            };
        });

        res.json(success(fullYearData));
    } catch (err) {
        console.error('获取统计数据失败:', err);
        res.json(error('获取统计数据失败', 500, err.message));
    }
});

module.exports = router; 